package com.infomanage.service.syscfg;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspWriter;

import com.infomanage.bean.FieldBean;
import com.infomanage.bean.PaginationBean;
import com.infomanage.bean.SearchBean;
import com.infomanage.dao.DeptDAO;
import com.infomanage.dao.UserDAO;
import com.infomanage.enums.RoleType;
import com.infomanage.exception.DaoException;
import com.infomanage.po.Department;
import com.infomanage.po.User;
import com.infomanage.util.Consts;
import com.infomanage.util.StringUtil;
import com.jiuqi.util.ReturnObject;
import com.jiuqi.util.StringUtils;

public class UserService {

	public static User loadUser(HttpServletRequest request, HttpServletResponse response, JspWriter out){
		try {
			request.setCharacterEncoding("UTF-8");
			String userId= request.getParameter("userId");
			if(StringUtils.isEmpty(userId)) return null;
			UserDAO dao = new UserDAO();
			return dao.find(User.class, Integer.parseInt(userId));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static List<User> loadUserList(HttpServletRequest request, HttpServletResponse response, JspWriter out){
		try {
			request.setCharacterEncoding("UTF-8");
			UserDAO dao = new UserDAO();
			List<User> list = dao.findAll(User.class);
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static ReturnObject saveUser(HttpServletRequest request, HttpServletResponse response, JspWriter out){
		ReturnObject ret = new ReturnObject();
		try {
			request.setCharacterEncoding("UTF-8");
			UserDAO dao = new UserDAO();
			if(dao.isExistUsername(request.getParameter("username"))){
				ret.SetErrored(true);
				ret.setErrorMessage("用户名已存在！");
				return ret;
			}
			User user = new User();
			user.setDeptLevel(converRoleToDeptLevel(Integer.parseInt(request.getParameter("roleId"))));
			user.setPassword(request.getParameter("password"));
			user.setRoleId(Integer.parseInt(request.getParameter("roleId")));
			user.setUserName(request.getParameter("username"));
			user.setPersonName(request.getParameter("personName"));
			user.setPersonId(Integer.parseInt(request.getParameter("personId")));
			user.setDescription(request.getParameter("description"));
			if(request.getParameter("associatedDept") != null){
				user.setAssociatedDept(Integer.parseInt(request.getParameter("associatedDept")));
			}
			dao.add(user);
		} catch (Exception e) {
			ret.SetErrored(true);
			ret.setErrorMessage(e.getMessage());
		}
		return ret;
	}
	
	public static ReturnObject modifyUser(HttpServletRequest request, HttpServletResponse response, JspWriter out){
		ReturnObject ret = new ReturnObject();
		try {
			request.setCharacterEncoding("UTF-8");
			UserDAO dao = new UserDAO();

			int userId = Integer.parseInt(request.getParameter("userId"));
			User user = dao.find(User.class, userId);
			if(!request.getParameter("username").equals(user.getUserName())){
				if(dao.isExistUsername(request.getParameter("username"))){
					ret.SetErrored(true);
					ret.setErrorMessage("用户名已存在！");
					return ret;
				}
			}
			user.setPassword(request.getParameter("password"));
			user.setRoleId(Integer.parseInt(request.getParameter("roleId")));
			user.setDeptLevel(converRoleToDeptLevel(Integer.parseInt(request.getParameter("roleId"))));
			user.setUserName(request.getParameter("username"));
			user.setPersonName(request.getParameter("personName"));
			user.setPersonId(Integer.parseInt(request.getParameter("personId")));
			user.setDescription(request.getParameter("description"));
			if(request.getParameter("associatedDept") != null){
				user.setAssociatedDept(Integer.parseInt(request.getParameter("associatedDept")));
			}
			dao.modify(user);
		} catch (Exception e) {
			ret.SetErrored(true);
			ret.setErrorMessage(e.getMessage());
		}
		return ret;
	}
	public static ReturnObject modifyPassword(HttpServletRequest request, HttpServletResponse response, JspWriter out){
		ReturnObject ret = new ReturnObject();
		try {
			request.setCharacterEncoding("UTF-8");
			int userId = Integer.parseInt(request.getParameter("userId"));
			UserDAO dao = new UserDAO();
			User user = dao.find(User.class, userId);
			user.setPassword(request.getParameter("password"));
			dao.modify(user);
		} catch (Exception e) {
			ret.SetErrored(true);
			ret.setErrorMessage(e.getMessage());
		}
		return ret;
	}
	
	public static ReturnObject removeUser(HttpServletRequest request, HttpServletResponse response, JspWriter out){
		ReturnObject ret = new ReturnObject();
		try {
			request.setCharacterEncoding("UTF-8");
			String planId = request.getParameter("userId");
			UserDAO dao = new UserDAO();
			dao.remove(User.class, Integer.parseInt(planId));
		} catch (Exception e) {
			ret.SetErrored(true);
			ret.setErrorMessage(e.getMessage());
		}
		return ret;
	}
	public static ReturnObject removeBatchUser(HttpServletRequest request, HttpServletResponse response, JspWriter out){
		ReturnObject ret = new ReturnObject();
		try {
			request.setCharacterEncoding("UTF-8");
			String batchIds = request.getParameter("batchIds");
			UserDAO dao = new UserDAO();
			if(batchIds != null){
				String[] ids = batchIds.split(";");
				for(String id : ids){
					dao.remove(User.class, Integer.parseInt(id));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			ret.SetErrored(true);
			ret.setErrorMessage("删除失败！");
		}
		return ret;
	}
	
	public static int converRoleToDeptLevel(int roleId){
		if(roleId == RoleType.SYSADMIN.value()){
			return 0;
		}else if(roleId == RoleType.DDADMIN.value()){
			return 1;
		}else if(roleId == RoleType.ZDADMIN.value()){
			return 2;
		}else if(roleId == RoleType.GENERALUSER.value()){
			return 3;
		}
		return roleId;
		
	}
	
	public static List<Department> listAssociatedDepts(){
		DeptDAO dao = new DeptDAO();
		try {
			return dao.findByLevel(2);
		} catch (DaoException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new ArrayList<Department>(1);
	}
	
	private static SearchBean buildSearchCondition(HttpServletRequest request, HttpServletResponse response,
			JspWriter out) throws Exception {
		request.setCharacterEncoding("UTF-8");
		String userName = request.getParameter("userName");
		String roleId = request.getParameter("roleId");
		SearchBean searchBean = new SearchBean();
		if (!StringUtil.isEmpty(userName)) {
			FieldBean field = new FieldBean("userName", userName);
			searchBean.add(field);
		}
		if (!StringUtil.isEmpty(roleId)) {
			FieldBean field = new FieldBean("roleId", Integer.parseInt(roleId));
			searchBean.add(field);
		}
		return searchBean;
	}
	
	public static int getPageCount(HttpServletRequest request, HttpServletResponse response, JspWriter out){
		try {
			UserDAO dao = new UserDAO();
			SearchBean searchBean = buildSearchCondition(request, response, out);
			return (dao.count(searchBean) + PaginationBean.pageSize - 1)/PaginationBean.pageSize;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 1;
	}
	
	public static List<User> search(HttpServletRequest request, HttpServletResponse response, JspWriter out) {
		try {
			request.setCharacterEncoding("UTF-8");
			UserDAO dao = new UserDAO();
			SearchBean searchBean = buildSearchCondition(request, response, out);
			//设置分页
			String currPageNum = request.getParameter("currPageNum");
			PaginationBean page = new PaginationBean();
			if(currPageNum == null){
				page.setCurrentPageNum(1);
			}else{
				page.setCurrentPageNum(Integer.parseInt(currPageNum));
				
			}
			searchBean.setPage(page);
			List<User> list = dao.findByFields(searchBean);
			User user = (User)request.getSession().getAttribute(com.infomanage.util.Consts.LOGINED_USER);
			List<User> finalList = new ArrayList<User>();
			if(user.getRoleId() == RoleType.SYSADMIN.value() && !Consts.SUPER_ADMIN_NAME.equals(user.getUserName())){
				for(User u : list){
					if(u.getUserName().equals(user.getUserName()) || u.getRoleId() != RoleType.SYSADMIN.value()){
						finalList.add(u);
					}
				}
			}else{
				finalList = list;
			}
			return finalList;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
